package com.umfwechat.lightprogram.controller.pos;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.umpay.sp.model.saas.AppChannel;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

 
import com.umfwechat.common.ReqMessage;
import com.umfwechat.common.code.RetCode;
import com.umfwechat.common.constant.CacheConsts;
import com.umfwechat.common.constant.CommonConsts;
import com.umfwechat.common.constant.ValueConsts;
import com.umfwechat.common.prop.UmfPropModel;
import com.umfwechat.lightprogram.vo.SetAgentRateCfg;
import com.umfwechat.util.DesIDUtil;
import com.umfwechat.util.GetWxAndLmf;
import com.umfwechat.util.PropertyUtil;
import com.umfwechat.util.RedisUtil;
import com.umfwechat.util.ReqMessageUtil;
import com.umfwechat.util.SaasPropertyUtil;
import com.umfwechat.util.StringUtil;
 import com.umfwechat.wx.service.WeixinService;
 import com.umpay.operation.model.qrConf.QrConf;
import com.umpay.operation.model.saas.StoreBatchDetail;
import com.umpay.operation.model.saas.StoreLictype;
import com.umpay.operation.model.spapplyplat.JoinFlow;
import com.umpay.operation.service.qrConf.remote.QrConfServiceRemote;
import com.umpay.operation.service.saas.TStoreBatchDetailServiceRemote;
import com.umpay.operation.service.saas.TStoreLictypeServiceRemote;
import com.umpay.operation.xml.XmlData;
import com.umpay.sp.model.common.ResMessage;
import com.umpay.sp.model.saas.RatesConf;
import com.umpay.sp.model.saas.StoreInf;
 import com.umpay.sp.service.saas.remote.AppChannelServiceRemote;
import com.umpay.sp.service.saas.remote.RatesServiceRemote;
import com.umpay.sp.service.saas.remote.StoreInfServiceRemote;
import com.umpay.sp.service.sys.remote.UserServiceRemote;
 @Controller
@RequestMapping("/newMerchantProductDeploy")
public class NewMerchantPosController {
	private static Logger logger = LoggerFactory.getLogger(NewMerchantPosController.class);
	//商户报备接口
	private static final String P2_0900 = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","P2_0900", "");
	//代理商装机区域查询
	private static final String P2_11250 =PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","p2.11250", "");
	//根据终端型号查询代理商可绑定SN号 
 	private static final String P2_0701 =PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","p2.0701", "");
 	//商户进件信息修改接口
	private static final String P2_0120 =PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","p2.0120", "");
	//更新上传状态
	private static final String P2_0117 =PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","p2.0117", "");
	//pos加密压缩包路径
	private static final String ZIPPATHSRC = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","posZipJMpath", "");
	//测试
	//private static final String ZIPPATHSRC = "D:/zipFile";
	//pos签约产品
	private static final String posProductId =PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","posProductId", "");
	//pos加密压缩包密码
	private static final String ZIPPWD = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","posZipJMPW", "");

	private static final String DATASOURCE = "SAAS";  //默认？
	@Resource
	private StoreInfServiceRemote storeInfServiceRemote;  
	//渠道service
	@Resource
	private AppChannelServiceRemote appChannelServiceRemote;
	//二维码绑定service
	@Resource
	private QrConfServiceRemote qrConfServiceRemote;
	//代理商费率配置
	@Resource
	private RatesServiceRemote ratesServiceRemote;	 
	//用户信息server
	@Resource
	private UserServiceRemote userServiceRemote_sp;
	//生成二维码service
	@Resource
	private WeixinService weixinService; 
	//资质照片
	@Resource
	private TStoreLictypeServiceRemote tStoreLictypeServiceRemote;
	//批量入网明细
	@Resource
	private TStoreBatchDetailServiceRemote tStoreBatchDetailServiceRemote;
	 
	
	@RequestMapping(value="/openPosSubmit",produces="application/json;charset=UTF-8")
	@ResponseBody
	@SuppressWarnings("unchecked")
	public JSONObject openPosSubmit(HttpServletRequest request, HttpServletResponse response) throws Exception{
		// 第一步  调代理商进件接口  
		logger.info("----*---------*--开通pos信息提交，开始--*---------*--");
		JSONObject resultJson = new JSONObject();
		String reqJSON = (String) request.getAttribute("_requestData");
		JSONObject json = null;
		try {
			json = JSONObject.fromObject(reqJSON);
		} catch (Exception e) {
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "请求参数不足");
			logger.error("----#---------#-开通pos信息提交,数据转换异常--#---------#--", e);
			return resultJson;
		}			
		String qrCodeList0 = json.optString("qrCodeList");	//收款码列表
		/**
		 * 获取店铺部署详情
		 */
		com.umpay.sp.model.common.ReqMessage reqStoreInf = ReqMessageUtil.makeSpReq();
		ResMessage resStoreInf = null;
		reqStoreInf.put("storeId",(String) json.get("storeId"));	//店铺编号
		try {
			logger.info("----#---------#--获取店铺部署详情，请求参数：--#---------#--" + reqStoreInf);
			resStoreInf = storeInfServiceRemote.getStoreInfByPri(reqStoreInf);
			logger.info("----#---------#--获取店铺部署详情，返回参数：--#---------#--" + resStoreInf);
		} catch (Exception e) {
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "服务器异常，请稍后再试");
			logger.error("----#---------#--获取店铺部署详情异常--#---------#--" + e);
			return resultJson;
		}
		if(!"0000".equals(resStoreInf.getRetCode())){	//查询店铺详情失败或异常
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "服务器异常，请稍后再试");
			return resultJson;
		}else if(resStoreInf.getResMap().get("storeInf") == null){	//未获取到店铺信息，storeId不存在
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "获取店铺信息失败");
			return resultJson;
		}
		
		StoreInf storeInf = (StoreInf) resStoreInf.getResMap().get("storeInf");
		String posMerId = storeInf.getPosReportId(); //从店铺表获取开通的posMerId
		//B2017121300000003
		String agentId = (String)json.get("loginAgentId");  
		String userId = (String)json.get("loginUserId");  //登录的userid
		String redisKey = "login"+agentId+userId;				
        //-------------取出缓存中的 assistid 和 password----------------------
        String redisValue = RedisUtil.get(redisKey);
        //userId,assistId,password,其他
        String [] strArr = redisValue.split(",");
        String assistid = strArr[1];
        logger.info("-----------------assistid-------------------- " + assistid);
        String password = strArr[2];
        logger.info("-----------------i know-------------------- " + password);
        String dataSource = DATASOURCE;	
        String applyShType = "0";  //申请商户类别 0:标准类 1:优惠类 2：减免类 (SAAS固定为0)
		String mernamesm = storeInf.getStoreShortName();  //商户简称
		if(!Pattern.matches("[a-zA-Z0-9\u4e00-\u9fa5]{6,16}",mernamesm)){
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "请修改店铺简称");
			return resultJson;
		}
		String busiName =  storeInf.getStoreFullName();  //11    必传，原企业全称    营业执照名称
		String occurArea = storeInf.getStoreAddrProv();  //必传，原主营业务          ---新增所在省
		//TODO  店铺表 0小微 1个体 2 企业 ---需修改
		String merNature ="";  //商户性质 必传，原商户类型0：企业 1：个人
		if("2".equals( storeInf.getStoreType())){
			merNature ="0";//0：企业 1：个人
		}else{
			merNature ="1";//0：企业 1：个人
		}
		String licenseNo =  storeInf.getLicenseNo(); //营业执照号
		String  vldEndDt =  changeDateFomate(storeInf.getCategoryInidcardValid());  //营业执照有效期	  yyyyMMdd								 
		
		//TODO
		String  dateOpen = changeDateFomate(storeInf.getRegisterDate());  //成立日期  15   个体是传原来的值，---企业时待确认  yyyyMMdd
		String  lawyer =  storeInf.getCategoryManName(); //法人姓名
		//TODO 新增字段 ---需修改
		String ciertiType = "0"; //法人证件类型  0:身份证 1：护照
		String certCode = DesIDUtil.decID(storeInf.getCategoryManCardno());  //法人证件号
		String majarBusi = storeInf.getMainBusiness();  //主营业务
		
		//TODO 新增字段
		String regAmt = "";   //C 注册资金（万元）21  当商户性质为企业（0）时必填    *100
		if("2".equals( storeInf.getStoreType())){
			//regAmt = String.valueOf(new BigDecimal("10.22").multiply(new BigDecimal(100)).intValue());//2：企业 1：个人
		}else{
			regAmt ="";// 1：个人
		}
		String empoNum = "5";   //员工数量s默认传5
		String provCode = storeInf.getStoreAddrProv();   //商户注册地址省份必传，原商户地址取省
		String areaCode = storeInf.getStoreAddrCity();   //商户注册地址城市必传，原商户地址取市
		String code = storeInf.getStoreAddrArea();   //C 商户注册地址区域
		
		String merAddr = storeInf.getStoreFullAddr();   // 商户注册地址详细地址 26 原详细地址（不是营业执照的注册地址）
		String hyType = (String)json.get("hyType");   // 商户所属行业类别 固定传 14                                  -----------
		//TODO 新增字段
		String  registrationNo = "";   //C 组织机构代码  当商户性质为企业（0）时必填
		String addBusiness = "0";   // 是否开通额外业务 固定 0
		String starttime = (String)json.get("starttime");   // 营业开始时间 格式HH:mm 例：09:00                   ------------
						
		String endtime = (String)json.get("endtime");   // 营业结束时间  31                                      -----------------
		String linkMan = storeInf.getPayeeName();   //必传，原收款人
		String mobileId =  storeInf.getPayeeMobileId();   // 必传，收款人手机号
		String linkManProvinceCode = storeInf.getStoreAddrProv();   //联系人地址省份- 必传，原商户地址（非营业执照的地址）
		String linkManCityCode = storeInf.getStoreAddrCity();   // 联系人地址城市 -必传，原商户地址（非营业执照的地址）					
		
		String linkManAddr =  storeInf.getStoreFullAddr();   // 36必传，原商户地址（非营业执照的地址）  联系人地址详细地址
		String zipCd = "100000";   // 邮编 固定 100000
		String  modelType ="1";   // 机具类型  必传固定值 1
		String  contrId = (String)json.get("contrId");   // 协议编号                          ---------------------
		String  remark = (String)json.get("remark");  //N 备注                                    ----------------------
		
		//String jfeerate = new BigDecimal((String)json.get("jfeerate")).multiply(new BigDecimal(100)).setScale(4,BigDecimal.ROUND_HALF_UP).toString();   // 41  借记卡费率（%）借记卡费率（%）页面填写的数据*100 （保留两位小数）。 ------------------
		//String debitCapamt = String.valueOf(new BigDecimal((String)json.get("debitCapamt")).multiply(new BigDecimal(100)).intValue());   //借记卡封顶金额（元）借记卡封顶金额（元）页面填写的数据*100     ---------------------
		//String dfeerate = new BigDecimal((String)json.get("dfeerate")).multiply(new BigDecimal(100)).setScale(4,BigDecimal.ROUND_HALF_UP).toString();   //贷记卡费率（%） 页面填写的数据*100保留两位小数                                                 ---------------------
		String jfeerate =(String)json.get("jfeerate");
		String debitCapamt =(String)json.get("debitCapamt");
		String dfeerate =(String)json.get("dfeerate");
		String dfeeCapamt = "0";   //贷记卡封顶金额（元） *100
		String getTermType = "1";   //机具模式必传固定值 1
		
		//String getTermAmt = String.valueOf(new BigDecimal((String)json.get("getTermAmt")).multiply(new BigDecimal(100)).intValue());   //4      6机具金额(元)-------- *100                         -----------------------
		String getTermAmt =(String)json.get("getTermAmt");
		String modelNames = (String)json.get("modelNames");   //必传，新  终端型号。 调用内部的配置接口只上传世麦P2000L和联迪E350 -----------------------
		String terminalNums = (String)json.get("terminalNums");   //   机具数量(个) 用“-”分隔（与终端型号一一对应）                          -----------------------
		//TODO 新增
		String snNumberNums = (String)json.get("snNumber");   //SN号例：CC000001,CC000002-XDL00001-LD000001, LD000002, LD000003（与终端型号和机具数量对应）-----------
		//TODO 新增
		String installAreaInf = (String)json.get("installAreaInf");   //装机区域  调用/11250 [0-9]{4}                     --------------------------
 		String installProvName = storeInf.getStoreAddrProv();   //商户装机地址省份 51必传，原商户地址（非营业执照的地址）
		String installCityName = storeInf.getStoreAddrCity();   // 商户装机地址城市 必传，原商户地址（非营业执照的地址）		
		String installAreaName =  storeInf.getStoreAddrArea();  //C//则可以不传该字段，若存在则必传	
		//TODO cehsi 有值的报错
	  	//installAreaName = "8200";
		//String installDetailAddr = "北京-北京市-西城区-"+storeInf.getStoreFullAddr();   //商户装机地址详细地址
		String installDetailAddr =  (String)json.get("installAddr")+"-"+storeInf.getStoreFullAddr();   //商户装机地址详细地址

		String preState = (String)json.get("preState");   //申请开通预授权 0：开通 1：不开通   --------------------
		
		String alipay = "0";   //支付宝 56   0：开通 1：不开通  SASS固定为0
		String arate = "";   //C 必传，新 支付宝费率--；调用接口时传递的参数与页面输入的值一致，参数保留四小数（数据库的值与页面值一致  -----------------------
		String wechat = "0";   //微信 固定值 00：开通 1：不开通Saas固定为0
		String wrate = "";   //C 微信费率必传，新必须为大于0的数字；调用接口时传递的参数与页面输入的值一致，参数保留四小数（数据库的值与页面值一致）----------------------		
		if("detail".equals((String)json.get("posFrom"))){
			logger.info("-------------------------补开查询费率开始----------------------");
			Map ss = getImPay((String)json.get("storeId"));
			logger.info("-------------------------补开查询费率结束----------------------");
			if(!"0000".equals(ss.get("retCode"))){
				resultJson.put("retCode", "0001");
			 	resultJson.put("retMsg", ss.get("retMsg"));
				return resultJson;
			}
			arate = ss.get("alipayRate").toString();
			wrate = ss.get("wechatRate").toString();
		}else{
			arate = (String)json.get("alipayRate");
			wrate =  (String)json.get("wechatRate");
			//arate = String.valueOf(new BigDecimal((String)json.get("alipayRate")).divide(new BigDecimal(100)));
			//wrate =  String.valueOf(new BigDecimal((String)json.get("wechatRate")).divide(new BigDecimal(100)));
		}
		arate =new BigDecimal(arate).multiply(new BigDecimal(1)).setScale(2,BigDecimal.ROUND_HALF_UP).toString();
		wrate =new BigDecimal(wrate).multiply(new BigDecimal(1)).setScale(2,BigDecimal.ROUND_HALF_UP).toString();
		//TODO 新增
		String ispayUmf = "1";   //0：开通 1：不开通 //默认不开通联动扫码
		String crate = "0";      //     默认费率为零
		String oneYardPay = "1";   //一码付61 --0：开通 1：不开通温馨提示：开通一码付需同时勾选微信和支付宝,或只勾选联动扫码,或三者全选saas固定值 1
		//TODO  ceshi
		String  alipayThreeId = ""; //C 支付宝经营三级类目-必传根据原有类目自动对应
		String  wechatThreeId = ""; //C 微信经营三级类目
		List<String> transResult  = GetWxAndLmf.getTransResult(storeInf.getStoreCategory().replace("&",""));		 
		if(transResult==null){//行业类目没有找到
			logger.info("没有找到对应行业类目");
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "没有找到对应行业类目");
			logger.info("----*---------*--没有找到对应行业类目--*---------*--");
			return resultJson;
		}else{
			logger.info( "：对应支付宝："+transResult.get(0)+"  对应微信:"+transResult.get(1));
			alipayThreeId=transResult.get(0);
			wechatThreeId=transResult.get(1);
		}
		//TODO
		String callbackUrl = (String)json.get("callbackUrl");   // 回调地址 规则见回调通知接口文档
		//ceshi
 		//TODO 新增
		String merchantId = storeInf.getStoreId();   // //内部商户号    商户号为子商户号必传

		String confMerId = storeInf.getMerId();  // //66   配置商户号 商户号为主商户号必传
		String isBlack = "0";  //固定值0（因为开通商户的接口已经调用了黑名单接口能走到POS的都不是黑名单商户）
		String inputSource = "02"; //Saas传02   若不传默认为00(线下自服务进件商户)
		String formId = (String)json.get("formId");
		
				
		Map<String, Object> reqMap1 = ReqMessageUtil.makeReqMap();   //请求web server的map										 						
		reqMap1.put("userid", userId);
		reqMap1.put("assistid", assistid);
		
		reqMap1.put("password", password);//6
		reqMap1.put("dataSource", dataSource);
		reqMap1.put("agentId", agentId);
		reqMap1.put("applyShType", applyShType);//0:标准类 1:优惠类 2：减免类(SAAS固定为0)
		reqMap1.put("mernamesm", mernamesm);//必传，原店铺简称
		
		reqMap1.put("busiName", busiName);//11    必传，原企业全称
		reqMap1.put("occurArea", occurArea);//必传，原主营业务                                         ---新增
		reqMap1.put("merNature", merNature);//必传，原商户类型0：企业 1：个人
		reqMap1.put("licenseNo", licenseNo);//必传，原营业执照号
		reqMap1.put("vldEndDt", vldEndDt);//营业执照有效期
		
		reqMap1.put("dateOpen", dateOpen);//15   个体是传原来的值，--------------企业时待确认----
		reqMap1.put("lawyer", lawyer);
		reqMap1.put("ciertiType", ciertiType);
		reqMap1.put("certCode", certCode);
		reqMap1.put("majarBusi", majarBusi);
		
		if(!StringUtil.isEmpty(regAmt)){
			reqMap1.put("regAmt",  regAmt);//21  当商户性质为企业（0）时必填  --------  *100
		}
		reqMap1.put("empoNum", empoNum);//s默认传5
		reqMap1.put("provCode", provCode);//必传，原商户地址取省
		reqMap1.put("areaCode", areaCode);//必传，原商户地址取市
		if(!StringUtil.isEmpty(code)){
			reqMap1.put("code", code);  //，则可以不传该字段，若存在则必传。
		}
		
		reqMap1.put("merAddr", merAddr);//26 原详细地址（不是营业执照的注册地址）
		reqMap1.put("hyType", hyType);//固定传 14
		if(!StringUtil.isEmpty(registrationNo)){
			reqMap1.put("registrationNo", registrationNo);//当商户性质为企业（0）时必填
		}
		reqMap1.put("addBusiness", addBusiness);//固定 0
		reqMap1.put("starttime", starttime);//格式HH:mm 例：09:00
		
		reqMap1.put("endtime", endtime);//31
		reqMap1.put("linkMan", linkMan);//必传，原收款人
		reqMap1.put("mobileId", mobileId);//必传，收款人手机号
		reqMap1.put("linkManProvinceCode", linkManProvinceCode);//必传，原商户地址（非营业执照的地址）
		reqMap1.put("linkManCityCode", linkManCityCode);//必传，原商户地址（非营业执照的地址）
		
		reqMap1.put("linkManAddr", linkManAddr);//36必传，原商户地址（非营业执照的地址）
		reqMap1.put("zipCd", zipCd);//固定 100000
		reqMap1.put("modelType", modelType);//必传固定值 1
		reqMap1.put("contrId", contrId);//协议编号
		if(!StringUtil.isEmpty(remark)){
			reqMap1.put("remark",remark);//备注
		}
		
		reqMap1.put("jfeerate", jfeerate);//41借记卡费率（%）--------------页面填写的数据*100 （保留两位小数）。
		reqMap1.put("debitCapamt", debitCapamt);//借记卡封顶金额（元）页面填写的数据*100 
		reqMap1.put("dfeerate", dfeerate);//贷记卡费率（%）页面填写的数据*100保留两位小数
		reqMap1.put("dfeeCapamt", dfeeCapamt);//贷记卡封顶金额（元）*100
		reqMap1.put("getTermType", getTermType);//机具模式 必传固定值 1

		reqMap1.put("getTermAmt", getTermAmt);//46机具金额(元)-------- *100
		reqMap1.put("modelNames", modelNames); //必传，新。 调用内部的配置接口只上传世麦P2000L和联迪E350
		reqMap1.put("terminalNums", terminalNums);//机具数量(个) 用“-”分隔（与终端型号一一对应）
		reqMap1.put("snNumberNums", snNumberNums);//SN号例：CC000001,CC000002-XDL00001-LD000001, LD000002, LD000003（与终端型号和机具数量对应）
		reqMap1.put("installAreaInf", installAreaInf);//装机区域  调用/11250 [0-9]{4}
		
		reqMap1.put("installProvName", installProvName);//51必传，原商户地址（非营业执照的地址）
		reqMap1.put("installCityName", installCityName);//必传，原商户地址（非营业执照的地址）
		if(!StringUtil.isEmpty(installAreaName)){
			reqMap1.put("installAreaName", installAreaName);//则可以不传该字段，若存在则必传
		}
		reqMap1.put("installAddr", installDetailAddr);
		reqMap1.put("preState", preState);//申请开通预授权0：开通 1：不开通
		
		reqMap1.put("alipay", alipay);//56   0：开通 1：不开通  SASS固定为0
		reqMap1.put("arate", arate);// 必传，新 支付宝费率--；调用接口时传递的参数与页面输入的值一致，参数保留四小数（数据库的值与页面值一致
		
		reqMap1.put("wechat", wechat);//固定值 00：开通 1：不开通Saas固定为0
		reqMap1.put("wrate", wrate);//微信费率必传，新必须为大于0的数字；调用接口时传递的参数与页面输入的值一致，参数保留四小数（数据库的值与页面值一致）		
		
		reqMap1.put("oneYardPay", oneYardPay);//61 --0：开通 1：不开通温馨提示：开通一码付需同时勾选微信和支付宝,或只勾选联动扫码,或三者全选saas固定值 1
		if(!StringUtil.isEmpty(alipayThreeId)){
			reqMap1.put("alipayThreeId", alipayThreeId);//支付宝经营三级类目--必传根据原有类目自动对应
		}
		if(!StringUtil.isEmpty(wechatThreeId)){
			reqMap1.put("wechatThreeId", wechatThreeId);//微信经营三级类目
		}
		reqMap1.put("callbackUrl", callbackUrl);//规则见回调通知接口文档
		reqMap1.put("merchantId", merchantId);//内部商户号    商户号为子商户号必传

		reqMap1.put("confMerId", confMerId);//66   配置商户号 商户号为主商户号必传
		reqMap1.put("isBlack", isBlack);//固定值0（因为开通商户的接口已经调用了黑名单接口能走到POS的都不是黑名单商户）
		reqMap1.put("inputSource", inputSource);//传02   若不传默认为00(线下自服务进件商户)
		reqMap1.put("crate", crate);//默认费率为零
		
		if(StringUtil.isNotEmpty(posMerId)){
			reqMap1.put("ispayUmf", ispayUmf);//默认不开通联动扫码
			reqMap1.put("merId", posMerId);//
			//修改pos信息
			Map<String,Object> fromWebServer = null;   //几次和web server的交互重复利用
			logger.info("----*---------*-- 商户进件信息修改接口提交,去访问  "+P2_0120 +" --*---------*--");
			try{
				logger.info("----*---------*--商户进件信息修改接口入参"+reqMap1);
 				fromWebServer  =  com.umpay.http.platform2.HttpUtil.httpPostForm2Xml
						(P2_0120, reqMap1,"GBK");  //代理商进件接口
				logger.info("----*---------*--商户进件信息修改接口出参"+fromWebServer.toString());
			}catch(Exception e){
				resultJson.put("retCode", "0001");
				resultJson.put("retMsg", "商户进件信息修改接口返回异常");
				logger.info("----*---------*--商户进件信息修改接口返回异常--*---------*--", e);
				return resultJson;
			}
 
			String retCode1 = (String)fromWebServer.get("retCode");
			String retMsg1 = (String)fromWebServer.get("retMsg");
			String ProMess1 = (String)fromWebServer.get("ProMess"); //只有在错误的时候才有具体值
			if(!"0000".equals(retCode1)){
				resultJson.put("retCode", "0001");
				resultJson.put("retMsg", "代理商进件接口返回异常");
				logger.info("----*---------*--商户进件信息修改接口互失败--*---------*--");
				logger.info("去0120接口   返回的retCode= "+retCode1+" retMsg= " + retMsg1 +" ProMess= "+ProMess1);
				return resultJson;
			}
			logger.info("----*---------*-保存formId--*---------*--");			 
 			storeInf.setFormId(formId);
			Map<String, String> storeMap = SaasPropertyUtil.javaBeanToMap(storeInf);
			com.umpay.sp.model.common.ReqMessage req = ReqMessageUtil.makeSpReq();   
			com.umpay.sp.model.common.ResMessage res = null;
			req.putAll(storeMap);   
			
			try {
				logger.info("----#---------#--更新店铺formId，请求参数：--#---------#--" + req);
				res = storeInfServiceRemote.updateStoreInf(req);
				logger.info("----#---------#--更新店铺formId，返回参数：--#---------#--" + res);
			} catch (Exception e) {
				resultJson.put("retCode", "0001");
				resultJson.put("retMsg", "服务器异常，请稍后再试");
				logger.info("----#---------#--更新店铺formId异常--#---------#--",e);
				return resultJson;
			}
			if(!"0000".equals(res.getRetCode())){
			 	resultJson.put("retCode", "0001");
			 	resultJson.put("retMsg", res.getRetMsg());
				return resultJson;
			}
			logger.info("----#---------#--保存formId成功：--#---------#--");
		}else{
			
			//开通pos信息
			reqMap1.put("ispayUMF", ispayUmf);//默认不开通联动扫码

			Map<String,Object> fromWebServer = null;   //几次和web server的交互重复利用
			try{
				logger.info("----*---------*--开通pos信息提交,去访问  "+P2_0900 +" --*---------*--");
				logger.info("----*---------*--开通pos信息提交入参"+reqMap1);
 				fromWebServer  =  com.umpay.http.platform2.HttpUtil.httpPostForm2Xml
						(P2_0900, reqMap1,"GBK");  //代理商进件接口
				logger.info("----*---------*--开通pos信息提交出参"+fromWebServer.toString());
			}catch(Exception e){
				resultJson.put("retCode", "0001");
				resultJson.put("retMsg", "代理商进件接口返回异常");
				logger.info("----*---------*--开通pos信息提交,代理商进件接口返回异常--*---------*--", e);
				return resultJson;
			}
	  //    处理第一次和web Server的交互 返回的报文
			String retCode1 = (String)fromWebServer.get("retCode");
			String retMsg1 = (String)fromWebServer.get("retMsg");
			String ProMess1 = (String)fromWebServer.get("ProMess"); //只有在错误的时候才有具体值
			if(!"0000".equals(retCode1)){
				resultJson.put("retCode", "0001");
				resultJson.put("retMsg", "代理商进件接口返回异常");
				logger.info("----*---------*--开通pos信息提交,第一次和企业web交互失败--*---------*--");
				logger.info("去0104接口   返回的retCode= "+retCode1+" retMsg= " + retMsg1 +" ProMess= "+ProMess1);
				return resultJson;
			}
			String merId = (String)fromWebServer.get("merId"); //开户成功时返回
			logger.info("----*---------*--修改店铺编号 保存pos报备编号--*---------*--");
			//TODO店铺报备编号
			storeInf.setPosReportId(merId);
			storeInf.setFormId(formId);
			Map<String, String> storeMap = SaasPropertyUtil.javaBeanToMap(storeInf);
			com.umpay.sp.model.common.ReqMessage req = ReqMessageUtil.makeSpReq();   
			com.umpay.sp.model.common.ResMessage res = null;
			req.putAll(storeMap);   
			
			try {
				logger.info("----#---------#--更新店铺报备编号，请求参数：--#---------#--" + req);
				res = storeInfServiceRemote.updateStoreInf(req);
				logger.info("----#---------#--更新店铺报备编号，返回参数：--#---------#--" + res);
			} catch (Exception e) {
				resultJson.put("retCode", "0001");
				resultJson.put("retMsg", "服务器异常，请稍后再试");
				logger.info("----#---------#--更新店铺报备编号异常--#---------#--",e);
				return resultJson;
			}
			if(!"0000".equals(res.getRetCode())){
			 	resultJson.put("retCode", "0001");
			 	resultJson.put("retMsg", res.getRetMsg());
				return resultJson;
			}
			logger.info("----#---------#--更新店铺报备编号成功：--#---------#--");
			posMerId =  merId;
		}
		//---------------------------------第2  上传资质照片-------------------------------------
		logger.info("----#---------#--上传资质照片  开始-#---------#--");
		//获取pos照片
		com.umpay.operation.common.ReqMessage req =  com.umfwechat.util.ReqMessageUtil.makeOpReq();		
		com.umpay.operation.common.ResMessage res = new com.umpay.operation.common.ResMessage();	
		req.put("storeId",storeInf.getStoreId());	//店铺编号
		req.put("licfileState","01");	//
		try {
			logger.info("【获取店铺资质】请求参数：" + req);
			res = tStoreLictypeServiceRemote.queryLictypeList(req);
			logger.info("【获取店铺资质】返回参数：" + res);
		} catch (Exception e) {
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "服务器异常，请稍后再试");
			logger.error("【获取店铺资质】异常", e);
			return resultJson;
		}
		if (!"0000".equals(res.getRetCode())) {
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "获取店铺资质失败");
			return resultJson;
		}
		List<StoreLictype>  storeLictypeList = (List<StoreLictype>) res.getResMap().get(XmlData.LICTYPE_LIST);
		Map retma = makeZip(storeInf,posMerId,storeLictypeList);
		if(!"0000".equals(retma.get("retCode"))){
			resultJson.put("retCode", "0001");
		 	resultJson.put("retMsg", retma.get("retMsg"));
			return resultJson;
		}
		logger.info("----#---------#--上传资质照片  结束-#---------#--");
		
		//---------------------------------第3 更新上传状态-------------------------------------

		logger.info("----#---------#--更新上传状态  开始-#---------#--");
		Map<String,Object> reqMap2 =ReqMessageUtil.makeReqMap();   
		reqMap2.put("agentId", agentId);
		reqMap2.put("userid", userId);
		reqMap2.put("assistid", assistid);
		reqMap2.put("password", password);
		reqMap2.put("dataSource", dataSource);			 
		reqMap2.put("merId",posMerId);
		reqMap2.put("oldisUpload","0");
		reqMap2.put("newisUpload","1");
		Map<String,Object> fromWebServer2 = null;   
		try{
			logger.info("----*---------*-更新上传状态,去访问  "+P2_0117 +" --*参数为"+reqMap2);
			fromWebServer2  =  com.umpay.http.platform2.HttpUtil.httpPostForm2Xml
        		(P2_0117, reqMap2,"GBK");
			logger.info("----*---------*--更新上传状态,出参  "+fromWebServer2);
		}catch(Exception e){
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "-更新上传状态接口返回异常");
			logger.info("----*---------*---更新上传状态返回异常--*---------*--" , e);
			return resultJson;
		}
		String retCode1 = (String)fromWebServer2.get("retCode");
		if(!"0000".equals(retCode1)){
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "更新上传状态接口返回异常");
			logger.info("----*---------*---更新上传状态接口返回异常--*---------*--");
			return resultJson;
		}
		logger.info("----#-------- ------------#--更新上传状态接口  结束-#---------#--");
		
  
		//---------------------------------第5  开通pos产品-------------------------------------
		logger.info("----# ----------------------#--开通pos产品  开始-#---------#--");
		Map reOpenImPay1 = posOpenImPay((String) json.get("storeId"));
		if(!"0000".equals(reOpenImPay1.get("retCode"))){
			resultJson.put("retCode", "0001");
		 	resultJson.put("retMsg", reOpenImPay1.get("retMsg"));
			return resultJson;
		}
		logger.info("----#-----------------------#--开通pos产品  结束-#---------#--");
		if("detail".equals((String)json.get("posFrom"))){
			resultJson.put("retCode", "0000");	
			resultJson.put("retMsg", "补开pos成功");
			return resultJson;
		} 
		//---------------------------------第5  开通立马付产品-------------------------------------
		logger.info("----# ----------------------#--开通立马付产品  开始-#---------#--");
		Map reOpenImPay = openImPay((String) json.get("storeId"),(String) json.get("wechatRate"),
				(String) json.get("alipayRate"),qrCodeList0,agentId);
		if(!"0000".equals(reOpenImPay.get("retCode"))){
			resultJson.put("retCode", "0001");
		 	resultJson.put("retMsg", reOpenImPay.get("retMsg"));
			return resultJson;
		}
		logger.info("----#---------#--开通立马付产品  结束-#---------#--");
    	resultJson.put("retCode", "0000");
     	resultJson.put("storeId", reOpenImPay.get("storeId"));
    	resultJson.put("payeeName",  reOpenImPay.get("payeeName"));
    	resultJson.put("storeShortName",  reOpenImPay.get("storeShortName"));
    	resultJson.put("qrCodeUrl",  reOpenImPay.get("qrCodeUrl"));
		return resultJson;
		
	}
	
	

	@RequestMapping(value="/getArea",produces="application/json;charset=UTF-8")
	@ResponseBody
	@SuppressWarnings("unchecked")
	public JSONObject getArea(HttpServletRequest request, HttpServletResponse response) throws Exception{	 
			logger.info("----*---------*--获取装机区域，开始--*---------*--");
			Map<String,Object>  resultMap = new HashMap<String,Object>();   //流程最后返回给小程序的map
		
			String reqJSON=(String) request.getAttribute("_requestData");
			JSONObject jsonFromLP = null;				
			try{
			jsonFromLP = JSONObject.fromObject(reqJSON);  
			}catch(Exception e){
				resultMap.put("retCode", "0001");
				resultMap.put("retMsg", "请求参数不足");
				logger.info("----*---------*---获取装机区域,数据转换异常--*---------*--" + e);
				return JSONObject.fromObject(resultMap);
			}
			
			
			String loginAgentId = (String)jsonFromLP.get("loginAgentId"); 
			String agentId = ""; 
			if(loginAgentId.contains("Y")){
				logger.info("当前为一级代理商：" + agentId);
				agentId = loginAgentId;
			}else{
				//获取一级代理商
				logger.info("--------需要查询一级代理商：");
				Map<String, Object> crmResult =null;
				Map<String, Object> params = ReqMessageUtil.makeReqCrmMap();
				params.put(CommonConsts.AGENTID, loginAgentId);
				params.put(CommonConsts.RELTYPE, "4");//	查询所有上级	
				try{
					XStream xstream = new XStream(new DomDriver());
					// URL配置文件取 --日志
		 			String url=UmfPropModel.INSTANCE.getPropValue("agent.crm.queryAgentRel");			
		 			logger.info("【查询代理商多级关系接口】入参url：" + url);
					logger.info("【查询代理商多级关系接口】入参params：" + params);
					crmResult =  (Map<String, Object>) com.umfwechat.util.HttpUtil.getResObjPost(url, xstream, params);	 
					logger.info("【查询代理商多级关系接口】出参：params" + crmResult);
				}catch(Exception e){
					resultMap.put("retCode", "0001");
					resultMap.put("retMsg", "查询代理商多级关系接口返回异常");
					logger.info("----*---------*---查询代理商多级关系接口返回异常--*---------*--");
					return JSONObject.fromObject(resultMap);			 
				}
				String retCode = (String) crmResult.get(CommonConsts.RETCODE);
				if (!RetCode.SUCCESS.equals(retCode)){
					resultMap.put("retCode", "0001");
					resultMap.put("retMsg", "查询代理商多级关系接口返回异常");
					logger.info("----*---------*---查询代理商多级关系接口返回异常--*---------*--");
					return JSONObject.fromObject(resultMap);
				}
				Map<String, Object> agentMetaMap =  (Map<String, Object>) crmResult.get("agentMetaMap");
				List s  = (List) agentMetaMap.get("agent[1]List");//取出一级代理商
				if(s == null && s.get(0)== null){
					resultMap.put("retCode", "0001");
					resultMap.put("retMsg", "查询代理商多级关系接口返回异常");
					logger.info("----*---------*---查询代理商多级关系接口返回异常--*---------*--");
					return JSONObject.fromObject(resultMap);
				}
				agentId =s.get(0).toString();
				logger.info("一级代理商为：" + agentId);
			}
			
			String userId = (String)jsonFromLP.get("loginUserId");  //登录的userid	
			String pageNo   = (String)jsonFromLP.get(CommonConsts.PAGE_NO);		 //pageNo  ：页数
			if(StringUtil.isEmpty(pageNo)){
				pageNo=ValueConsts.PAGE_ONE;
			}
			String pageSize =(String)jsonFromLP.get(CommonConsts.PAGE_SIZE);	//每页条数
			if(StringUtil.isEmpty(pageSize)){
				pageSize=ValueConsts.PAGE_TWENTY;
			}					      		
			String redisKey = "login"+agentId+userId;		
			
	        //-------------取出缓存中的 assistid 和 password----------------------
	        String redisValue = RedisUtil.get(redisKey);
	        //userId,assistId,password,其他
	        String [] strArr = redisValue.split(",");
	        String assistid = strArr[1];
	        logger.info("-----------------assistid-------------------- " + assistid);
	        String password = strArr[2];
	        logger.info("-----------------i know-------------------- " + password);
	        String dataSource = DATASOURCE;	
	        List<Map> retuStr = new ArrayList<Map>();
			Map<String,Object> reqMap1 =ReqMessageUtil.makeReqMap();   //请求web server的map
			
							
			reqMap1.put("agentId", agentId);
			reqMap1.put("userid", userId);
			reqMap1.put("assistid", assistid);
			reqMap1.put("password", password);
			reqMap1.put("dataSource", dataSource);
			
			reqMap1.put("pageNum", "1");
			reqMap1.put("pageSize", "10000");
			reqMap1.put("state","'2'");
						
			Map<String,Object> fromWebServer = null;   
			try{
				logger.info("----*---------*--获取装机区域,去访问  "+P2_11250 +" --*参数为"+reqMap1);
				fromWebServer  =  com.umpay.http.platform2.HttpUtil.httpPostForm2Xml
	        		(P2_11250, reqMap1,"GBK");  //代理商进件接口
				logger.info("----*---------*--获取装机区域出参  "+fromWebServer);
			}catch(Exception e){
				resultMap.put("retCode", "0001");
				resultMap.put("retMsg", "-获取装机区域接口返回异常");
				logger.info("----*---------*---获取装机区域信息提交,获取装机区域接口返回异常--*---------*--" + e);
				return JSONObject.fromObject(resultMap);
			}
      //    处理第一次和web Server的交互 返回的报文
			String retCode1 = (String)fromWebServer.get("retCode");
			String retMsg1 = (String)fromWebServer.get("retMsg");													
			if(!"0000".equals(retCode1)){
				resultMap.put("retCode", "0001");
				resultMap.put("retMsg", "获取装机区域接口返回异常");
				logger.info("----*---------*---获取装机区域接口返回异常--*---------*--");
				return JSONObject.fromObject(resultMap);
			}
		   /* String listStr =  (String) fromWebServer.get("list");	   
		    if(listStr != null){
				JSONArray jArray = JSONArray.fromObject(listStr);
				 for(int i=0 ; i < jArray.size() ;i++){
					    //获取每一个JsonObject对象
					    JSONObject myjObject = jArray.getJSONObject(i);						    
					    //获取每一个对象中的值
					    String checkStateAudit = myjObject.getString("checkStateAudit");
					    String state = myjObject.getString("state");
					   if("N".equals(checkStateAudit) && "2".equals(state)){
						   Map s =new HashMap<>();
						   s.put("areaId", myjObject.getString("areaId"));
						   s.put("areaName", myjObject.getString("areaName"));
						   retuStr.add(s);
					   }						   
				 }	    		
			}*/
		   Object listStr = null;
		   listStr = fromWebServer.get("list");
		   resultMap.put("retCode", "0000");
		   resultMap.put("list", listStr);
		   return JSONObject.fromObject(resultMap);
		
	}	
	@RequestMapping(value="/getSn",produces="application/json;charset=UTF-8")
	@ResponseBody
	@SuppressWarnings("unchecked")
	public JSONObject getSn(HttpServletRequest request, HttpServletResponse response) throws Exception{	 
			logger.info("----*---------*--终端型号sn查询，开始--*---------*--");
			Map<String,Object>  resultMap = new HashMap<String,Object>();   //流程最后返回给小程序的map
		
			String reqJSON=(String) request.getAttribute("_requestData");
			JSONObject jsonFromLP = null;				
			try{
			jsonFromLP = JSONObject.fromObject(reqJSON);  
			}catch(Exception e){
				resultMap.put("retCode", "0001");
				resultMap.put("retMsg", "请求参数不足");
				logger.info("----*---------*---终端型号查询,数据转换异常--*---------*--" + e);
				return JSONObject.fromObject(resultMap);
			}
			
			
			String loginAgentId = (String)jsonFromLP.get("loginAgentId");  
			String agentId = ""; 
			if(loginAgentId.contains("Y")){
				logger.info("-----------当前为一级代理商：" + agentId);
				agentId = loginAgentId;
			}else{
				//获取一级代理商		
				logger.info("--------需要查询一级代理商：");
				Map<String, Object> crmResult =null;
				Map<String, Object> params = ReqMessageUtil.makeReqCrmMap();
				params.put(CommonConsts.AGENTID, loginAgentId);
				params.put(CommonConsts.RELTYPE, "4");//	查询所有上级	
				try{
					XStream xstream = new XStream(new DomDriver());
					// URL配置文件取 --日志
		 			String url=UmfPropModel.INSTANCE.getPropValue("agent.crm.queryAgentRel");			
		 			logger.info("【查询代理商多级关系接口】入参url：" + url);
					logger.info("【查询代理商多级关系接口】入参params：" + params);
					crmResult =  (Map<String, Object>) com.umfwechat.util.HttpUtil.getResObjPost(url, xstream, params);	 
					logger.info("【查询代理商多级关系接口】出参：params" + crmResult);
				}catch(Exception e){
					resultMap.put("retCode", "0001");
					resultMap.put("retMsg", "查询代理商多级关系接口返回异常");
					logger.info("----*---------*---查询代理商多级关系接口返回异常--*---------*--");
					return JSONObject.fromObject(resultMap);			 
				}
				String retCode = (String) crmResult.get(CommonConsts.RETCODE);
				if (!RetCode.SUCCESS.equals(retCode)){
					resultMap.put("retCode", "0001");
					resultMap.put("retMsg", "查询代理商多级关系接口返回异常");
					logger.info("----*---------*---查询代理商多级关系接口返回异常--*---------*--");
					return JSONObject.fromObject(resultMap);
				}
				Map<String, Object> agentMetaMap =  (Map<String, Object>) crmResult.get("agentMetaMap");
				List s  = (List) agentMetaMap.get("agent[1]List");//取出一级代理商
				if(s == null && s.get(0)== null){
					resultMap.put("retCode", "0001");
					resultMap.put("retMsg", "查询代理商多级关系接口返回异常");
					logger.info("----*---------*---查询代理商多级关系接口返回异常--*---------*--");
					return JSONObject.fromObject(resultMap);
				}
				agentId =s.get(0).toString();
				logger.info("一级代理商为：" + agentId);
			}
			String userId = (String)jsonFromLP.get("loginUserId");  //登录的userid	
			String modelName = (String)jsonFromLP.get("modelName");  //终端型号

			String pageNo   = (String)jsonFromLP.get(CommonConsts.PAGE_NO);		 //pageNo  ：页数
			if(StringUtil.isEmpty(pageNo)){
				pageNo=ValueConsts.PAGE_ONE;
			}
			String pageSize =(String)jsonFromLP.get(CommonConsts.PAGE_SIZE);	//每页条数
			if(StringUtil.isEmpty(pageSize)){
				pageSize=ValueConsts.PAGE_TWENTY;
			}					      		
			String redisKey = "login"+agentId+userId;		
			
	        //-------------取出缓存中的 assistid 和 password----------------------
	        String redisValue = RedisUtil.get(redisKey);
	        //userId,assistId,password,其他
	        String [] strArr = redisValue.split(",");
	        String assistid = strArr[1];
	        logger.info("-----------------assistid-------------------- " + assistid);
	        String password = strArr[2];
	        logger.info("-----------------i know-------------------- " + password);
	        String dataSource = DATASOURCE;	
	        List  retuStr = new ArrayList();
			Map<String,Object> reqMap1 =ReqMessageUtil.makeReqMap();   //请求web server的map
			
							 
			reqMap1.put("agentId", agentId);
			reqMap1.put("userid", userId);
			reqMap1.put("assistid", assistid);
			reqMap1.put("password", password);
			reqMap1.put("dataSource", dataSource);			
			reqMap1.put("pageNum", "1");
			reqMap1.put("pageSize", "1000");
			reqMap1.put("modelName", modelName);
			reqMap1.put("isAgentSelf","1");			
			Map<String,Object> fromWebServer = null;   
			try{
				logger.info("----*---------*--终端型号sn查询,去访问  "+P2_0701 +" --*参数为"+reqMap1);
				fromWebServer  =  com.umpay.http.platform2.HttpUtil.httpPostForm2Xml
	        		(P2_0701, reqMap1,"GBK");  //代理商进件接口
				logger.info("----*---------*--终端型号sn查询出参  "+fromWebServer);
			}catch(Exception e){
				resultMap.put("retCode", "0001");
				resultMap.put("retMsg", "-终端型号sn查询返回异常");
				logger.info("----*---------*---终端型号sn查询信息提交,终端型号查询接口返回异常--*---------*--" + e);
				return JSONObject.fromObject(resultMap);
			}
      //    处理第一次和web Server的交互 返回的报文
			String retCode1 = (String)fromWebServer.get("retCode");
			String retMsg1 = (String)fromWebServer.get("retMsg");													
			if(!"0000".equals(retCode1)){
				resultMap.put("retCode", "0001");
				resultMap.put("retMsg", "获取终端型号sn查询接口返回异常");
				logger.info("----*---------*---获取终端型号sn查询接口返回异常--*---------*--");
			    return JSONObject.fromObject(resultMap);

			}
		    Object listStr =   fromWebServer.get("list");	   				
		    resultMap.put("retCode", "0000");
		    resultMap.put("list", listStr);
		    return JSONObject.fromObject(resultMap);
		
	}	
	//压缩包上传
	@RequestMapping(value="/makeZip",produces="application/json;charset=UTF-8")
	@ResponseBody
	@SuppressWarnings("unchecked")
	public Map makeZip(StoreInf storeInf,String posMerId, List<StoreLictype> storeLictypeList){
		

		Map<String,Object> resultMap = new HashMap<String,Object>();
		//创建目录
		String zipPath = ZIPPATHSRC+File.separator+posMerId.substring(1,9);
		File zipDir = new File(zipPath);   //创建存放zip的目录
	    if(!zipDir.exists()){
	    	zipDir.mkdir();
	    	logger.info(zipPath,"----*---------*创建存放zip目录--不存在   ---创建----*---------*--");
	    }
    	logger.info("-------------存在存放zip目录-------------"+zipPath);  //看到结尾带 "/"  
    	//创建zip
 	    String zipFilePath = zipPath+ File.separator + posMerId + ".zip";   //压缩文件路径
	    logger.info("----*---------*--压缩包路径 "+zipFilePath+" ----*---------*--");	    
	    try {
            //创建zip文件
		    ZipFile zipFile = new ZipFile(zipFilePath);	  
            //增加文件到zip中
             ArrayList<File> filesToAdd = new ArrayList<File>();
		    if("0".equals(storeInf.getType())){
		    	//单个入网
		    	logger.info("-------------单个入网获取照片zip-------------"+zipPath);
	            filesToAdd = makeFileList(storeInf,storeLictypeList);
		    }else if("1".equals(storeInf.getType())){
		    	//批量入网
		    	logger.info("-------------批量入网获取照片zip-------------"+zipPath);
		    	
				//查询批量明细表,获取照片路径	
				com.umpay.operation.common.ReqMessage req =  com.umfwechat.util.ReqMessageUtil.makeOpReq();		
				com.umpay.operation.common.ResMessage res = new com.umpay.operation.common.ResMessage();	
		  		req.put("storeId",storeInf.getStoreId());
 		  		logger.info("【查询批量明细列表信息】入参：" + req);
		 		res = tStoreBatchDetailServiceRemote.queryBatchDetailList(req);
				logger.info("【查询批量明细列表信息】出参：" + res);
		 		if(!"0000".equals(res.getRetCode())){
					logger.info("统计批量明细列表查询失败");
 			    	resultMap.put("retCode", "0001");
			    	resultMap.put("retMsg", "统计批量明细列表查询失败");
					return resultMap;
				}
				List<StoreBatchDetail> storeBatchDetails = (List<StoreBatchDetail>) res.getResMap().get(XmlData.STORE_BATCH_DETAIL_LIST);	
				if(storeBatchDetails == null){
					logger.info("统计批量明细列表查询为空");
 			    	resultMap.put("retCode", "0001");
			    	resultMap.put("retMsg", "统计批量明细列表查询为空");
					return resultMap;
				}
				if(StringUtil.isEmpty(storeBatchDetails.get(0).getImgUrl())){
					logger.info("批量入网商户未上传照片");
 			    	resultMap.put("retCode", "0001");
			    	resultMap.put("retMsg", "批量入网商户未上传照片");
					return resultMap;
				}
				String posZip = storeBatchDetails.get(0).getImgUrl();
		    	filesToAdd = makeFileListType(storeInf,storeLictypeList,posZip);
		    }
            
           
             //初始化各类参数
            ZipParameters parameters = new ZipParameters();
            //设置压缩模式
            parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
            parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
            //设置加密标志
            parameters.setEncryptFiles(true);
            //设置aes加密
            parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
            parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
            //设置密码
            parameters.setPassword(ZIPPWD);    

            File file=new File(zipFilePath);
            if(file.exists()&&file.isFile()){
                logger.info("----*---------*--已上传过压缩包，删除原压缩包"+zipFilePath);
                file.delete();
            }
			zipFile.addFiles(filesToAdd, parameters);
	 
        }
        catch (Exception e){
        	logger.info("----*---------*--压缩包打包失败 \n",e);
	    	resultMap.put("retCode", "0001");
	    	resultMap.put("retMsg", "压缩包打包失败");
			return resultMap;
        } 
	    	
	    
	    logger.info("ZIPIMG end:" + new Date());	    	          
		logger.info("----*---------*--create "+zipFilePath+" successfully--*---------*--");
		resultMap.put("retCode", "0000");
		return resultMap;
	}
	private ArrayList<File> makeFileListType(StoreInf storeInf,
			List<StoreLictype> storeLictypeList, String posZip) {
		ArrayList<File> filesToAdd = new ArrayList<File>();
		String imgFileUrl = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","saasPlat.comp.uploadPath", "");	//获取图片服务器存储地址
		logger.info("---------照片配置路径"+imgFileUrl);
		String storeUrl = imgFileUrl +File.separator+ storeInf.getStoreId() + "/";
				
		String imgFileUrlPos = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","plzipLocation", "");	//获取图片服务器存储地址
		logger.info("---------批量入网照片配置路径"+imgFileUrl);
		String posUrl = imgFileUrlPos +File.separator+ posZip;
		//取出批量入网的压缩包
		if(new File(posUrl).exists()){	    		
    			logger.info("-------------poszip---存在----------"+posUrl);
                filesToAdd.add(new File(posUrl));
        }else{
        	logger.info("-------------poszip 不存在------------"+posUrl);
        }
			
		if(null != storeLictypeList){
			for(StoreLictype s :storeLictypeList){
				if(new File(storeUrl+ s.getLictypePath()).exists()){	    		
		    			logger.info("-------------posimg存在-------------"+storeUrl+ s.getLictypePath());
		                filesToAdd.add(new File(storeUrl+  s.getLictypePath()));
		        }else{
		        	logger.info("-------------posimg不存在-------------"+storeUrl+ s.getLictypePath());
		        }
			}
		}
 		return filesToAdd;
	}



	private ArrayList<File> makeFileList(StoreInf storeInf, List<StoreLictype> storeLictypeList) {
		ArrayList<File> filesToAdd = new ArrayList<File>();
		String imgFileUrl = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","saasPlat.comp.uploadPath", "");	//获取图片服务器存储地址
		logger.info("---------照片配置路径"+imgFileUrl);
		String storeUrl = imgFileUrl +File.separator+ storeInf.getStoreId() + "/";
		//8张照片	
		//-----------1
		if(StringUtil.isNotEmpty(storeInf.getPayeeCardPhotoFront())){
			if(new File(storeUrl+ storeInf.getPayeeCardPhotoFront()).exists()){	    		
	    		   // path  ="D:/SaasImg/68000250/3a862756ef3a43c7bf3e1c96898f8407.jpg";
	    			logger.info("-------------img存在-------------"+storeUrl+ storeInf.getPayeeCardPhotoFront());
	                filesToAdd.add(new File(storeUrl+ storeInf.getPayeeCardPhotoFront()));
	        }else{
	        	logger.info("-------------img不存在-------------"+storeUrl+ storeInf.getPayeeCardPhotoFront());
	        }
		}
		//-----------2
		if(StringUtil.isNotEmpty(storeInf.getPayeeCardPhotoCon())){
			if(new File(storeUrl+ storeInf.getPayeeCardPhotoCon()).exists()){	    		
	    		   // path  ="D:/SaasImg/68000250/3a862756ef3a43c7bf3e1c96898f8407.jpg";
	    			logger.info("-------------img存在-------------"+storeUrl+ storeInf.getPayeeCardPhotoCon());
	                filesToAdd.add(new File(storeUrl+ storeInf.getPayeeCardPhotoCon()));
	        }else{
	        	logger.info("-------------img不存在-------------"+storeUrl+ storeInf.getPayeeCardPhotoCon());
	        }
		}
		//-----------3
		if(StringUtil.isNotEmpty(storeInf.getCategoryCardPhotoFront())){
			if(new File(storeUrl+ storeInf.getCategoryCardPhotoFront()).exists()){	    		
	    		   // path  ="D:/SaasImg/68000250/3a862756ef3a43c7bf3e1c96898f8407.jpg";
	    			logger.info("-------------img存在-------------"+storeUrl+ storeInf.getCategoryCardPhotoFront());
	                filesToAdd.add(new File(storeUrl+ storeInf.getCategoryCardPhotoFront()));
	        }else{
	        	logger.info("-------------img不存在-------------"+storeUrl+ storeInf.getCategoryCardPhotoFront());
	        }
		}
		//-----------4
		if(StringUtil.isNotEmpty(storeInf.getCategoryCardPhotoCon())){
			if(new File(storeUrl+ storeInf.getCategoryCardPhotoCon()).exists()){	    		
	    		   // path  ="D:/SaasImg/68000250/3a862756ef3a43c7bf3e1c96898f8407.jpg";
	    			logger.info("-------------img存在-------------"+storeUrl+ storeInf.getCategoryCardPhotoCon());
	                filesToAdd.add(new File(storeUrl+ storeInf.getCategoryCardPhotoCon()));
	        }else{
	        	logger.info("-------------img不存在-------------"+storeUrl+ storeInf.getCategoryCardPhotoCon());
	        }
		}
		//-----------5
		if(StringUtil.isNotEmpty(storeInf.getShopSignPhotoFront())){
			if(new File(storeUrl+ storeInf.getShopSignPhotoFront()).exists()){	    		
	    		   // path  ="D:/SaasImg/68000250/3a862756ef3a43c7bf3e1c96898f8407.jpg";
	    			logger.info("-------------img存在-------------"+storeUrl+ storeInf.getShopSignPhotoFront());
	                filesToAdd.add(new File(storeUrl+ storeInf.getShopSignPhotoFront()));
	        }else{
	        	logger.info("-------------img不存在-------------"+storeUrl+ storeInf.getShopSignPhotoFront());
	        }
		}
		//-----------6
		if(StringUtil.isNotEmpty(storeInf.getShopSignPhotoCon())){
			if(new File(storeUrl+ storeInf.getShopSignPhotoCon()).exists()){	    		
	    		   // path  ="D:/SaasImg/68000250/3a862756ef3a43c7bf3e1c96898f8407.jpg";
	    			logger.info("-------------img存在-------------"+storeUrl+ storeInf.getShopSignPhotoCon());
	                filesToAdd.add(new File(storeUrl+ storeInf.getShopSignPhotoCon()));
	        }else{
	        	logger.info("-------------img不存在-------------"+storeUrl+ storeInf.getShopSignPhotoCon());
	        }
		}
		//-----------7
		if(StringUtil.isNotEmpty(storeInf.getBusiLicensePhoto())){
			if(new File(storeUrl+ storeInf.getBusiLicensePhoto()).exists()){	    		
	    		   // path  ="D:/SaasImg/68000250/3a862756ef3a43c7bf3e1c96898f8407.jpg";
	    			logger.info("-------------img存在-------------"+storeUrl+ storeInf.getBusiLicensePhoto());
	                filesToAdd.add(new File(storeUrl+ storeInf.getBusiLicensePhoto()));
	        }else{
	        	logger.info("-------------img不存在-------------"+storeUrl+ storeInf.getBusiLicensePhoto());
	        }
		}
		//-----------8
		if(StringUtil.isNotEmpty(storeInf.getAuthCertPhoto())){
			if(new File(storeUrl+ storeInf.getAuthCertPhoto()).exists()){	    		
	    		   // path  ="D:/SaasImg/68000250/3a862756ef3a43c7bf3e1c96898f8407.jpg";
	    			logger.info("-------------img存在-------------"+storeUrl+ storeInf.getAuthCertPhoto());
	                filesToAdd.add(new File(storeUrl+ storeInf.getAuthCertPhoto()));
	        }else{
	        	logger.info("-------------img不存在-------------"+storeUrl+ storeInf.getAuthCertPhoto());
	        }
		}	
		if(null != storeLictypeList){
			for(StoreLictype s :storeLictypeList){
				if(new File(storeUrl+ s.getLictypePath()).exists()){	    		
		    			logger.info("-------------posimg存在-------------"+storeUrl+ s.getLictypePath());
		                filesToAdd.add(new File(storeUrl+  s.getLictypePath()));
		        }else{
		        	logger.info("-------------posimg不存在-------------"+storeUrl+ s.getLictypePath());
		        }
			}
		}
 		return filesToAdd;
	}



	private Map posOpenImPay(String storeId) {
		Map<String,Object> json = new HashMap<String,Object>();
		json.put("retCode", "0000");
		json.put("retMsg", "成功");
		com.umpay.sp.model.common.ReqMessage reqChannel = ReqMessageUtil.makeSpReq();
		reqChannel.put("appSysId", storeId);
		reqChannel.put("mainProductId", "S000041");//pos大产品号
		//查询签约产品接口
		ResMessage resChannel =null;
		try {
			logger.info("查询签约产品接口入参："+reqChannel.toString());
			resChannel = appChannelServiceRemote.queryListAppChannel(reqChannel);
			logger.info("查询签约产品接口出参："+resChannel.toString());
		} catch (Exception e) {
			json.put("retCode", "0001");
			json.put("retMsg","调用渠道列表查询接口异常");
			logger.info("调用渠道列表查询接口异常：",e);
			return json;
		}
		//判断返回码是否是0000
		String codeChannel = resChannel.getRetCode();
		if(codeChannel.equals("0000")){	
			//已经申请过签约,就修改签约
			
		}else{
			//没有申请过签约，就申请签约产品
			com.umpay.sp.model.common.ReqMessage reqChannelS = ReqMessageUtil.makeSpReq();
			reqChannelS.put("appSysId", storeId);
 			reqChannelS.put("productId", posProductId);
			reqChannelS.put("state", "4");	
			reqChannelS.put("mainProductId", "S000041");			
			ResMessage resChannelS =null;
			try {
				logger.info("插入签约产品接口入参："+reqChannelS.toString());
				resChannelS=appChannelServiceRemote.insertChannel(reqChannelS);
				logger.info("插入签约产品接口出参："+resChannelS.toString());
			} catch (Exception e) {
				json.put("retCode", "0001");
				json.put("retMsg","调用渠道开通接口异常");
				logger.info("调用渠道开通接口异常：",e);
				return json;
			}
			//判断返回码是否是0000
			String codeChannelS = resChannelS.getRetCode();
			if(!codeChannelS.equals("0000")){	
				json.put("retCode", "0001");
				json.put("retMsg","渠道开通接口开通失败");
				return json;
			}
		}
		
		return json;
	}
	private Map getImPay(String storeId) {
		Map<String,Object> json = new HashMap<String,Object>();
		json.put("retCode", "0000");
		json.put("retMsg", "成功");
		//查询该店铺开通的立马付费率信息
		com.umpay.sp.model.common.ReqMessage reqMap = ReqMessageUtil.makeSpReq();
		reqMap.put("appSysId", storeId);	//应用编号
		String productIddg=PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","productId_impay_added", "");
		logger.info("取出配置文件参数productId_impay_added ="+productIddg);
		String productIdpl=PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","productId_impay", "");
		logger.info("取出配置文件参数productId_impay ="+productIdpl);		
		reqMap.put("productIds", "'"+productIddg+"','"+productIdpl+"'");	//产品编号
		ResMessage resMessage =null;
		try {
			//resMessage = appChannelServiceRemote.queryByAppSysId(req);
			logger.info("【查询签约的产品信息】入参："+reqMap.toString());
			resMessage = appChannelServiceRemote.getAppChannelListByProductids(reqMap);
			logger.info("【查询签约的产品信息】出参："+resMessage.toString());
		} catch (Exception e) {
			json.put("retCode", "0001");
			json.put("retMsg", "查询签约的产品信息异常");
			logger.info("查询签约的产品信息异常",e);
			return json;
		}
		//判断返回码是否是0000
		String retCode = resMessage.getRetCode();
		if(retCode.equals("0000")){	//查询到店铺数量>0
			Map<String, Object> map = resMessage.getResMap();
//					AppChannel appChannel = (AppChannel) map.get(com.umpay.sp.xml.XmlData.APPCHANNEL);	
			List<AppChannel> appChannelList = (List<AppChannel>) map.get("appChannelList");
			if(null==appChannelList||appChannelList.isEmpty()){
				json.put("retCode", "0001");
				json.put("retMsg", "查询费率为空");
				return json;
			}
			AppChannel appChannel =appChannelList.get(0);
			Integer wecatRates = appChannel.getWecatRates();	//微信费率
			Integer alipayRates =  appChannel.getAlipayRates();	//支付宝费率
			Double wxr=Double.valueOf(wecatRates)/1000;
			Double apr=Double.valueOf(alipayRates)/1000;
			json.put("alipayRate", apr);
			json.put("wechatRate", wxr);
		}else{
			json.put("retCode", "0001");
			json.put("retMsg", resMessage.getRetMsg());
			return json;
		}
		
		return json;
	}
	private Map openImPay(String storeId,String wechatRate,String alipayRate,String qrCodeList0,String agentId) throws Exception {
		Map<String,Object> json = new HashMap<String,Object>();
		json.put("retCode", "0000");
		json.put("retMsg", "成功");
// 		String storeId = storeId;	//店铺编号
//		String wechatRate =wechatRate;	//微信费率
//		String alipayRate = alipayRate;	//支付宝费率
//		String qrCodeList0 = qrCodeList0;	//收款码列表
		if(qrCodeList0==null || "".equals(qrCodeList0)){	//收款码列表为空时，赋值为空数组字符串
			qrCodeList0="[]";
		}
//		String agentId = param.optString("loginAgentId");	//代理商编号
//		
		logger.info("参数：qrCodeList0"+qrCodeList0);

		JSONArray fromObject = JSONArray.fromObject(qrCodeList0);
		String[] qrCodeList=new String[fromObject.size()];	
		//创建一个数组，将前端传递的数组字符串放进去
		int i=0;
		for (Object object : fromObject) {
			qrCodeList[i]=object.toString();
			i++;
		}
		//校验联动给代理商设置的费率
		//TODO
		com.umfwechat.common.ReqMessage reqMessage = ReqMessageUtil.makeReq();
		Map<String,Object> reqMap = reqMessage.getReqMap();
		reqMap.put("rpid", reqMessage.getRpid());
		reqMap.put("reqDate", reqMessage.getReqDate());
		reqMap.put("reqTime", reqMessage.getReqTime());
		reqMap.put("agentId", agentId);
		String agentProfitType=PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","agentProfitType", "");
		reqMap.put("type", agentProfitType);	//定价产品 type就传 10，传0时有数据方便测试
		Map<String,Object> frontResult = null;
		try {
			logger.info("调用联动给代理商设置的费率接口入参："+reqMap.toString());
			String agentProfitUrl=PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","agentProfitUrl", "");	//http://10.10.77.88:18888
			frontResult = com.umpay.http.platform2.HttpUtil.httpPostForm2Xml
					(agentProfitUrl, reqMap);
			logger.info("调用联动给代理商设置的费率接口出参："+frontResult.toString());
		} catch (Exception e2) {
			json.put("retCode", "0001");
			json.put("retMsg","调用费率查询接口异常");
			logger.info("调用费率查询接口异常：",e2);
			return json;
		}
		String retCodeP2 = (String) frontResult.get("retCode");
		double lowRateStander=200d;
		if(retCodeP2.equals("0000")){
			String listString = (String)frontResult.get("list");
			if(listString != null){
				JSONArray jArray = JSONArray.fromObject(listString);
				List<SetAgentRateCfg> list =jArray.toList(jArray, SetAgentRateCfg.class);
				//循环查询到的费率，将最低值中的较大者取出来
				logger.info("调用联动给代理商设置的费率list："+list.toString());
				//循环查询到的费率，将最低值中的较大者取出来
				for (SetAgentRateCfg sa : list) {
					String sDate = sa.getStartDate();
					String eDate = sa.getEndDate();
					DateFormat df=new SimpleDateFormat("yyyyMMdd");
					long startDate = df.parse(sDate).getTime();
					long endDate = df.parse(eDate).getTime();
					long nowDate=new Date().getTime();
					logger.info("有效开始时间"+startDate+"有效结束时间:"+endDate+"现在时间："+nowDate);
					if(startDate<=nowDate && nowDate<=endDate){
						if("25".equals(sa.getRuleValue())){
							double fratVal=Double.parseDouble((sa.getFratVal()));
							lowRateStander = fratVal*100000;	//"fratVal": "0.001234"	
						}
					}
				}
			}
		}else{
			json.put("retCode", "0001");
			json.put("retMsg","调用费率查询接口失败"+frontResult.get("retMsg"));
			return json;
		}
		logger.info("调用联动给代理商设置的费率接口得到最低费率为："+lowRateStander/100000);
		//查询代理商设置的立马付费率接口
		com.umpay.sp.model.common.ReqMessage req = ReqMessageUtil.makeSpReq();
		req.put("agentId", agentId);
		ResMessage res = null;
		try {
			logger.info("查询代理商设置的立马付费率接口入参："+req.toString());
			res = ratesServiceRemote.getRatesByAgentId(req);
			logger.info("查询代理商设置的立马付费率接口出参："+res.toString());
		} catch (Exception e) {
			json.put("retCode", "0001");
			json.put("retMsg", "查询代理商费率配置异常，请稍后重试");
			logger.info("调用查询店铺列表异常失败：",e);
			return json;
		}
		//判断返回码是否是0000
		String code = res.getRetCode();
		if(code.equals("0000")){	
			Map<String, Object> map = res.getResMap();
			RatesConf ratesConf=(RatesConf) map.get("ratesConf");
			if(ratesConf==null){
				json.put("retCode", "0001");
				json.put("retMsg","没有查询到代理商上配置的费率信息");
				return json;
			}
			double highRate = Double.valueOf(ratesConf.getHighRate())*1000;
			double lowRate = Double.valueOf(ratesConf.getLowRate())*1000;
			double wxr=Double.valueOf(StringUtil.trim(wechatRate))*1000;
			if(wxr < lowRate || wxr >highRate || wxr<lowRateStander || wxr>10000){	//费率必须在代理商设置的最高和最低范围内，并且不能低于联动给代理商设置的最低费率，并且费率不得大于10%
				json.put("retCode", "0001");
				json.put("retMsg","设置的费率必须在"+lowRate/1000+"到"+highRate/1000+"范围内"+",并且费率大于等于"+lowRateStander/1000);
				return json;
			}
			double apr=Double.valueOf(StringUtil.trim(alipayRate))*1000;
			if(apr < lowRate || apr >highRate || apr<lowRateStander || apr>10000){
				json.put("retCode", "0001");
				json.put("retMsg","设置的费率必须在"+lowRate/1000+"到"+highRate/1000+"范围内"+",并且费率大于等于"+lowRateStander/1000);
				return json;
			}
			
			com.umpay.sp.model.common.ReqMessage reqChannel = ReqMessageUtil.makeSpReq();
			reqChannel.put("appSysId", storeId);
			reqChannel.put("mainProductId", "S000040");
			//查询签约产品接口
			ResMessage resChannel =null;
			try {
				logger.info("查询签约产品接口入参："+reqChannel.toString());
				resChannel = appChannelServiceRemote.queryListAppChannel(reqChannel);
				logger.info("查询签约产品接口出参："+resChannel.toString());
			} catch (Exception e) {
				json.put("retCode", "0001");
				json.put("retMsg","调用渠道列表查询接口异常");
				logger.info("调用渠道列表查询接口异常：",e);
				return json;
			}
			//判断返回码是否是0000
			String codeChannel = resChannel.getRetCode();
			if(codeChannel.equals("0000")){	
				//已经申请过签约,就修改签约
				com.umpay.sp.model.common.ReqMessage reqChannelX = ReqMessageUtil.makeSpReq();
				reqChannelX.put("appSysId", storeId);
				//String productId=PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","productId_impay", "");
				List<AppChannel> resultList = (List<AppChannel>) resChannel.getValue("resultList");
				reqChannelX.put("productId", resultList.get(0).getProductId());				
//				reqChannelX.put("state", "4"); //状态不做处理
				reqChannelX.put("appName", "立马付");
				reqChannelX.put("mainProductId", "S000040");
				
				reqChannelX.put("alipayRates",String.valueOf((int)apr));	//c存整数，0.38%=38/10000
				reqChannelX.put("wecatRates",String.valueOf((int)wxr));
				ResMessage resChannelX =null;
				try {
					logger.info("修改签约产品接口入参："+reqChannelX.toString());
					resChannelX=appChannelServiceRemote.updateChannel(reqChannelX);
					logger.info("修改签约产品接口出参："+resChannelX.toString());
				} catch (Exception e) {
					json.put("retCode", "0001");
					json.put("retMsg","调用渠道修改接口异常");
					logger.info("调用渠道修改接口异常：",e);
					return json;
				}
				//判断返回码是否是0000
				String codeChannelX = resChannelX.getRetCode();
				if(!codeChannelX.equals("0000")){	
					json.put("retCode", "0001");
					json.put("retMsg","渠道修改接口修改失败");
					return json;
				}
			}else{
				//没有申请过签约，就申请签约产品
				com.umpay.sp.model.common.ReqMessage reqChannelS = ReqMessageUtil.makeSpReq();
				reqChannelS.put("appSysId", storeId);
				String productId=PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","productId_impay", "");
				reqChannelS.put("productId", productId);
				reqChannelS.put("state", "4");	
				reqChannelS.put("appName", "立马付");
				reqChannelS.put("mainProductId", "S000040");
				reqChannelS.put("alipayRates", String.valueOf((int)apr));
				reqChannelS.put("wecatRates", String.valueOf((int)wxr));
				ResMessage resChannelS =null;
				try {
					logger.info("插入签约产品接口入参："+reqChannelS.toString());
					resChannelS=appChannelServiceRemote.insertChannel(reqChannelS);
					logger.info("插入签约产品接口出参："+resChannelS.toString());
				} catch (Exception e) {
					json.put("retCode", "0001");
					json.put("retMsg","调用渠道开通接口异常");
					logger.info("调用渠道开通接口异常：",e);
					return json;
				}
				//判断返回码是否是0000
				String codeChannelS = resChannelS.getRetCode();
				if(!codeChannelS.equals("0000")){	
					json.put("retCode", "0001");
					json.put("retMsg","渠道开通接口开通失败");
					return json;
				}
			}
			//校验收款码是否已经绑定过，即收款码是否可用
			List<String> qrCodes=new ArrayList<String>();
			for (String qrId : qrCodeList) {
				com.umpay.operation.common.ReqMessage reqQrConf = ReqMessageUtil.makeOpReq();
				reqQrConf.put("qrId", qrId);
				com.umpay.operation.common.ResMessage resreqQrConf =null;
				try {
					logger.info("查询收款码接口入参："+reqQrConf.toString());
					resreqQrConf=qrConfServiceRemote.queryQrConfByKey(reqQrConf);
					logger.info("查询收款码接口出参："+resreqQrConf.toString());
				} catch (Exception e) {
					json.put("retCode", "0001");
					json.put("retMsg","根据主键查询收款码接口异常");
					logger.info("根据主键查询收款码接口异常：",e);
					return json;
				}
				String retCodeQrConf = resreqQrConf.getRetCode();
				if(retCodeQrConf.equals("0000")){	//查询到了，就说明该收款码已经被绑定
					QrConf qrConf=(QrConf)resreqQrConf.getValue("qrConf");
					logger.info(qrId+"绑定的商户为"+qrConf);
					String merId = qrConf.getMerId();
					if("".equals(merId)){	//商户号没值，说明未绑定过，就将该收款码放入新的集合中
						qrCodes.add(qrId);
						continue;
					}else if(storeId.equals(merId)){	//判断二维码是否是被该店铺绑定的，如果是，就不放入新集合
						continue;
					}else{
						json.put("retCode", "0001");
						json.put("retMsg",qrId+"收款码已经商户"+merId+"被绑定");
						return json;
					}
				}else{
					json.put("retCode", "0001");
					json.put("retMsg",qrId+"该收款码无效");
					return json;
				}
			}
			//先查询店铺详细信息，绑定收款码时使用店铺名称
			com.umpay.sp.model.common.ReqMessage reqStore = ReqMessageUtil.makeSpReq();
			reqStore.put("storeId", storeId);
			ResMessage resStore =null;
			try {
				logger.info("【根据店铺编号查询店铺信息接口】入参："+reqStore.toString());
				resStore = storeInfServiceRemote.getStoreInfByPri(reqStore);	//根据店铺编号查询店铺信息
				logger.info("【根据店铺编号查询店铺信息接口】出参："+resStore.toString());
			} catch (Exception e1) {
				json.put("retCode", "0001");
				json.put("retMsg","查询店铺详情接口异常");
				logger.info("查询店铺详情接口异常：",e1);
				return json;
			}
			String retCodeStore = resStore.getRetCode();
			StoreInf storeInf =null;
			if(retCodeStore.equals("0000")){
				storeInf = (StoreInf) resStore.getResMap().get("storeInf");
				if(storeInf==null){
					json.put("retCode", "0001");
					json.put("retMsg", "查询店铺详情没有查询到");
					return json;
				}
			}else{
				json.put("retCode", "0001");
				json.put("retMsg", "查询店铺详情没有查询到"+resStore.getRetMsg());
				return json;
			}
			//绑定收款码
			for (String qrId : qrCodes) {
				com.umpay.operation.common.ReqMessage reqQrConf = ReqMessageUtil.makeOpReq();
				reqQrConf.put("qrId", qrId);
				reqQrConf.put("qrState", "1");
				reqQrConf.put("merId", storeId);
				reqQrConf.put("merName", storeInf.getStoreShortName());	//商户名称
				reqQrConf.put("goodsName", "立马付");	//商品名称
				String notifyUrl = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","notifyurl", "");	
				reqQrConf.put("notifyUrl", notifyUrl);	//回调路径
				
				com.umpay.operation.common.ResMessage resreqQrConf =null;
				try {
					logger.info("绑定收款码接口入参："+reqQrConf.toString());
					resreqQrConf=qrConfServiceRemote.updateQrConfByQrId(reqQrConf);
					logger.info("绑定收款码接口出参："+resreqQrConf.toString());
				} catch (Exception e) {
					json.put("retCode", "0001");
					json.put("retMsg","根据主机查询收款码接口异常");
					logger.info("根据主机查询收款码接口异常：",e);
					return json;
				}
				String retCodeQrConf = resreqQrConf.getRetCode();
				if(!retCodeQrConf.equals("0000")){
					json.put("retCode", "0001");
					json.put("retMsg","绑定收款码失败"+resreqQrConf.getRetMsg());
					return json;
				}
			}
			
			//根据主商户号查询是否开通过主用户
			String isHaveOpenUser="0"; //是否开通过主用户，0没有开通，1开通过
			Integer userId=null;	//主用户id，二维码场景值使用
			com.umpay.sp.model.common.ReqMessage reqUser = ReqMessageUtil.makeSpReq();
			reqUser.put("merFlag", storeInf.getMerId());
			reqUser.put("currentPage", "1");
			reqUser.put("pageSize", "4");
			ResMessage resUser =null;
			try {
				logger.info("【查询用户列表接口】入参："+reqUser.toString());
				resUser = userServiceRemote_sp.queryList(reqUser);	//根据主商户号查询是否创建过主用户
				logger.info("【查询用户列表接口】出参："+resUser.toString());
			} catch (Exception e) {
				json.put("retCode", "0001");
				json.put("retMsg","根据主商户号查询是否开通过主用户接口异常");
				logger.info("根据主商户号查询是否开通过主用户接口异常：",e);
				return json;
			}
			String retCodeUser = resUser.getRetCode();
			if(retCodeUser.equals("0000")){
				List<Map<String, Object>> resultList=(List<Map<String, Object>>)resUser.getResMap().get(XmlData.RESULT_LIST);
				if(resultList.size()==0){
					isHaveOpenUser="0";
				}else{
					isHaveOpenUser="1";
					Map<String, Object> resultmap = resultList.get(0);
					userId=(Integer)resultmap.get("userId");
				}
			}else{
				json.put("retCode", "0001");
				json.put("retMsg",resUser.getRetMsg());
				return json;
			}
			if(isHaveOpenUser.equals("0")){ //没有开通过主用户，就开通主用户，再开通子用户
				//开通主用户
				ResMessage resOpenUserM =null;
				try {
					resOpenUserM = openUser(storeInf.getMerId(), storeInf.getPayeeName(), storeInf.getPayeeName(), storeInf.getPayeeMobileId());
				} catch (Exception e) {
					json.put("retCode", "0001");
					json.put("retMsg","添加管理员接口异常");
					logger.info("添加管理员接口异常：",e);
					return json;
				}
				String retCodeOpenUserM = resOpenUserM.getRetCode();
				if(retCodeOpenUserM.equals("0000")){
					userId=(Integer)resOpenUserM.getValue(XmlData.USERID);
				}else{
					json.put("retCode", "0001");
					json.put("retMsg","添加管理员接口失败"+resOpenUserM.getRetMsg());		//该server错误时没有返回信息，只有错误码
					return json;
				}
				//开通子用户
				ResMessage resOpenUserO =null;
				try {
					resOpenUserO = openUser(storeId, storeInf.getPayeeName(), storeInf.getPayeeName(), storeInf.getPayeeMobileId());
				} catch (Exception e) {
					json.put("retCode", "0001");
					json.put("retMsg","添加管理员接口异常");
					logger.info("添加管理员接口异常：",e);
					return json;
				}
				String retCodeOpenUserO = resOpenUserO.getRetCode();
				if(!retCodeOpenUserO.equals("0000")){
					json.put("retCode", "0001");
					json.put("retMsg","添加管理员接口失败");		//该server错误时没有返回信息，只有错误码
					return json;
				}
			}else{	//开通过主用户，就判断是否开通过子用户
				//判断是否开通过子用户
				com.umpay.sp.model.common.ReqMessage reqUserO = ReqMessageUtil.makeSpReq();
				reqUserO.put("merFlag", storeId);
				reqUserO.put("currentPage", "1");
				reqUserO.put("pageSize", "4");
				ResMessage resUserO =null;
				try {
					logger.info("【查询用户列表接口】入参："+reqUserO.toString());
					resUserO = userServiceRemote_sp.queryList(reqUserO);	//根据店铺编号查询是否创建过子用户
					logger.info("【查询用户列表接口】出参："+resUserO.toString());
				} catch (Exception e) {
					json.put("retCode", "0001");
					json.put("retMsg","根据店铺编号查询是否开通过子用户接口异常");
					logger.info("根据店铺编号查询是否开通过子用户接口异常：",e);
					return json;
				}
				String retCodeUserO = resUserO.getRetCode();
				if(retCodeUserO.equals("0000")){
					List<Map<String, Object>> resultList=(List<Map<String, Object>>)resUserO.getResMap().get(XmlData.RESULT_LIST);
					if(resultList.size()==0){	//没有开通过子用户
						//开通子用户
						ResMessage resOpenUserO =null;
						try {
							resOpenUserO = openUser(storeId, storeInf.getPayeeName(), storeInf.getPayeeName(), storeInf.getPayeeMobileId());
						} catch (Exception e) {
							json.put("retCode", "0001");
							json.put("retMsg","添加管理员接口异常");
							logger.info("添加管理员接口异常：",e);
							return json;
						}
						String retCodeOpenUserO = resOpenUserO.getRetCode();
						if(!retCodeOpenUserO.equals("0000")){
							json.put("retCode", "0001");
							json.put("retMsg","添加管理员接口失败");		//该server错误时没有返回信息，只有错误码
							return json;
						}
					}
				}else{
					json.put("retCode", "0001");
					json.put("retMsg",resUser.getRetMsg());
					return json;
				}
			}
			String state =storeInf.getRegisterProcsState();
			if(state.equals("04")){	//待开通产品时就修改店铺的状态为05待邀请商户
				com.umpay.sp.model.common.ReqMessage reqStoreU = ReqMessageUtil.makeSpReq();
				storeInf.setIntime(null);
				storeInf.setModtime(null);
				storeInf.setRegisterProcsState("05");
				Map<String, String> storeMap = SaasPropertyUtil.javaBeanToMap(storeInf);
				reqStoreU.putAll(storeMap);
				//修改店铺状态
				ResMessage resStoreU =null;
				try {
					logger.info("【更新店铺接口】入参："+reqStoreU.toString());
					resStoreU = storeInfServiceRemote.updateStoreInf(reqStoreU);
					logger.info("【更新店铺接口】出参："+resStoreU.toString());
				} catch (Exception e) {
					json.put("retCode", "0001");
					json.put("retMsg","更新店铺状态接口异常");
					logger.info("更新店铺状态接口异常：",e);
					return json;
				}
				String retCodeStoreU = resStoreU.getRetCode();
				if(!retCodeStoreU.equals("0000")){	//没有更新成功
					json.put("retCode", "0001");
					json.put("retMsg",resStoreU.getRetMsg());
					return json;
				}
			}
			//生成公众号二维码
			Integer scene_id=userId;
			Integer time=24*60*60;
			String expireTime=time.toString();//24小时
			String qrCodeUrl;
			try {
				logger.info("【生成二维码接口】入参：scene_id="+userId+"expireTime="+expireTime);
				qrCodeUrl = weixinService.getTicketQrCode(expireTime,scene_id);
				logger.info("【生成二维码接口】出参："+qrCodeUrl);
			} catch (Exception e) {
				json.put("retCode", "0001");
				json.put("retMsg", "获取二维码异常，稍后重试");
				logger.info("获取二维码异常：",e);
				return json;
			}
			json.put("storeId", storeInf.getStoreId());
			json.put("payeeName", storeInf.getPayeeName());
			json.put("storeShortName", storeInf.getStoreShortName());
			json.put("qrCodeUrl", qrCodeUrl);
			StringBuffer sb = new StringBuffer();
			long currentTime = new Date().getTime();
			sb.append(userId).append(",").append(expireTime).append(",").append(String.valueOf(currentTime)).append(",").append(qrCodeUrl);
			RedisUtil.set(CacheConsts.REDIS_QRCODE+storeId, 2592000, sb.toString());	//缓存起来,缓存30天
			logger.info("redis缓存中保存的信息为key为："+storeId+"value为："+sb.toString());
		}else{
			json.put("retCode", "0001");
			json.put("retMsg",res.getRetMsg());
		}
		
		return json;
 	}
	/**
	 * 添加管理员
	 * @param req
	 * @throws Exception 
	 */
	private ResMessage openUser(String merId,String logName,String name, String telephoneNo) throws Exception{
		com.umpay.sp.model.common.ReqMessage req=ReqMessageUtil.makeSpReq();
		req.put(XmlData.TELEPHONENO, telephoneNo);
		req.put(XmlData.MERID, merId);
		req.put(XmlData.LOGNAME, "admin");
		req.put(XmlData.NAME, name);
		//TODO 
		req.put("servId", merId);//商户编号
		req.put("servType", "11");// 业务类型 银行卡 11电子渠道 12 话费 13 U付14 兑换券 21 U付导入41
		req.put("role", "10");
		req.put(XmlData.LOGIN_PASSWD, "111111");
		ResMessage res =null;
		logger.info("【添加管理员接口】入参："+req.toString());
		res = userServiceRemote_sp.addAdminUser(req);
		logger.info("【添加管理员接口】出参："+res.toString());
		return res;
	}
	public String changeDateFomate(String curDate){
			return curDate.substring(0,4)+curDate.substring(5,7)+curDate.substring(8);
	}	
	/**
	 * pos会显
	 * @author ChenFuLong 2017-05-19
	 * @param session
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/getPosPhoto", produces="application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject merchantDetail(HttpSession session,HttpServletRequest request, HttpServletResponse response) throws Exception{
		logger.info("----#---------#--获取店铺部署详情，开始--#---------#--");
		JSONObject resultJson = new JSONObject();
		String reqJSON = (String) request.getAttribute("_requestData");
		JSONObject json = null;
		try {
			json = JSONObject.fromObject(reqJSON);
		} catch (Exception e) {
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "请求参数不足");
			logger.error("----#---------#--请求自助部署列表数据转换异常--#---------#--" + e);
			return resultJson;
		}
		String storeId = (String) json.get("storeId");	//店铺编号
		if (StringUtil.isEmpty(storeId)) {
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "请求参数不足");
			logger.info("----#---------#--获取店铺部署详情，请求参数不足--#---------#--");
			return resultJson;
		}
		/**
		 * 获取店铺部署详情
		 */
		com.umpay.sp.model.common.ReqMessage reqStoreInf = ReqMessageUtil.makeSpReq();
		ResMessage resStoreInf = null;
		reqStoreInf.put("storeId",storeId);	//店铺编号
		try {
			logger.info("----#---------#--获取店铺部署详情，请求参数：--#---------#--" + reqStoreInf);
			resStoreInf = storeInfServiceRemote.getStoreInfByPri(reqStoreInf);
			logger.info("----#---------#--获取店铺部署详情，返回参数：--#---------#--" + resStoreInf);
		} catch (Exception e) {
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "服务器异常，请稍后再试");
			logger.error("----#---------#--获取店铺部署详情异常--#---------#--" + e);
			return resultJson;
		}
		if(!"0000".equals(resStoreInf.getRetCode())){	//查询店铺详情失败或异常
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "服务器异常，请稍后再试");
			return resultJson;
		}else if(resStoreInf.getResMap().get("storeInf") == null){	//未获取到店铺信息，storeId不存在
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "获取店铺信息失败");
			return resultJson;
		}
		
		StoreInf storeInf = (StoreInf) resStoreInf.getResMap().get("storeInf");
				
		String imgHttpUrl = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","img.http.url", "");	//获取图片服务器Http地址
		String imgFileUrl = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","saasPlat.comp.uploadPath", "");	//获取图片服务器存储地址
		logger.info("----#---------#--获取umfWeChatPlat_appConf.properties配置文件中的参数--#---------#--" + imgHttpUrl + imgFileUrl);
		resultJson.put("retCode", "0000");	//
		resultJson.put("retMsg", "成功");	//
		
		resultJson.put("payeeCardPhotoFrontUrl", storeInf.getPayeeCardPhotoFront().equals("") ? storeInf.getPayeeCardPhotoFront() : imgHttpUrl + imgFileUrl + storeInf.getStoreId() + "/" + storeInf.getPayeeCardPhotoFront());	//收款人身份证正面
		resultJson.put("payeeCardPhotoConUrl", storeInf.getPayeeCardPhotoCon().equals("") ? storeInf.getPayeeCardPhotoCon() : imgHttpUrl + imgFileUrl + storeInf.getStoreId() + "/" + storeInf.getPayeeCardPhotoCon());	//收款人身份证反面
		resultJson.put("categoryCardPhotoFrontUrl", storeInf.getCategoryCardPhotoFront().equals("") ? storeInf.getCategoryCardPhotoFront() : imgHttpUrl + imgFileUrl + storeInf.getStoreId() + "/" + storeInf.getCategoryCardPhotoFront());	//经营者身份证正面
		resultJson.put("categoryCardPhotoCon", storeInf.getCategoryCardPhotoCon().equals("") ? storeInf.getCategoryCardPhotoCon() : imgHttpUrl + imgFileUrl + storeInf.getStoreId() + "/" + storeInf.getCategoryCardPhotoCon());	//经营者身份证反面
		resultJson.put("shopSignFrontUrl", storeInf.getShopSignPhotoFront().equals("") ? storeInf.getShopSignPhotoFront() : imgHttpUrl + imgFileUrl + storeInf.getStoreId() + "/" + storeInf.getShopSignPhotoFront());	//店铺招牌图片地址
		resultJson.put("shopInUrl", storeInf.getShopSignPhotoCon().equals("") ? storeInf.getShopSignPhotoCon() : imgHttpUrl + imgFileUrl + storeInf.getStoreId() + "/" + storeInf.getShopSignPhotoCon());	//店铺内景图片地址
		resultJson.put("storeLicenseNoUrl", storeInf.getBusiLicensePhoto().equals("") ? storeInf.getBusiLicensePhoto() : imgHttpUrl + imgFileUrl + storeInf.getStoreId() + "/" + storeInf.getBusiLicensePhoto());	//营业执照图片地址
		resultJson.put("authCertUrl", storeInf.getAuthCertPhoto().equals("") ? storeInf.getAuthCertPhoto() : imgHttpUrl + imgFileUrl + storeInf.getStoreId() + "/" + storeInf.getAuthCertPhoto());	//授权函图片地址
		
		com.umpay.operation.common.ReqMessage req =  com.umfwechat.util.ReqMessageUtil.makeOpReq();		
		com.umpay.operation.common.ResMessage res = new com.umpay.operation.common.ResMessage();
		
		req.put("storeId",storeInf.getStoreId());	//店铺编号
		req.put("licfileState","01");	//
		try {
			logger.info("【获取店铺资质】请求参数：" + req);
			res = tStoreLictypeServiceRemote.queryLictypeList(req);
			logger.info("【获取店铺资质】返回参数：" + res);
		} catch (Exception e) {
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "服务器异常，请稍后再试");
			logger.error("【获取店铺资质】异常", e);
			return resultJson;
		}
		if (!"0000".equals(res.getRetCode())) {
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "获取店铺资质失败");
			return resultJson;
		}
		List<StoreLictype>  storeLictypeList = (List<StoreLictype>) res.getResMap().get(XmlData.LICTYPE_LIST);
		if(null != storeLictypeList){
			for(StoreLictype s :storeLictypeList){
				resultJson.put(s.getLictypeId(),s.getLictypePath().equals("") ? s.getLictypePath() : imgHttpUrl + imgFileUrl + storeInf.getStoreId() + "/" + s.getLictypePath());
			}
		}
		return resultJson;
	}
}
